﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using NHibernate;
using hbse.Entities;
using hbse.DTO;
using hbse.Service;

namespace hbse
{
    public partial class Uscore : UserControl
    {
        private TabItem newTab;
        private DevComponents.DotNetBar.TabControl tabControl2;
        private ISession session;
        private Users users;
        private UntilService untilService = new UntilService();
        private SampleFolderMService sampleFolderMService = new SampleFolderMService();
        private NamePlateCoreService namePlateCoreService = new NamePlateCoreService();
        private Users user;

        private List<DTO.ProductSamMDTO> productSamMDTOs = new List<ProductSamMDTO>();
        private DTO.ProductSamMDTO productSamMDTO = null;

        private BarTender.ApplicationClass btApp;
        private BarTender.Format btformat;


        public Uscore(DevComponents.DotNetBar.TabControl _tabControl2, TabItem _newTab, ISession _session, Users _users)
        {
            InitializeComponent();
            newTab = _newTab;
            tabControl2 = _tabControl2;
            session = _session;
            users = _users;

            try
            {
                btApp = new BarTender.ApplicationClass();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        
        }

        private void Uscore_Load(object sender, EventArgs e)
        {

        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
              
            
                hbse.DTO.OrderDTO orderDTO = untilService.getOrderBySaleOrder(txtSearch.Text.Trim(),session);
                
                // ตรวจสอบ product มีลูกหรือไม่
                Product mproduct = sampleFolderMService.getByCode(orderDTO.ProductCode, session);

                // ถ้าไม่มีลูก
                if (mproduct.ProductType == "0")
                {
                    productSamMDTO = new ProductSamMDTO();
                    productSamMDTO.ProductCode = mproduct.ProductCode;
                    productSamMDTO.AC = mproduct.ProductAc;
                    productSamMDTO.AR = mproduct.ProductAr;
                    productSamMDTO.GAB = mproduct.ProductGab;
                    productSamMDTO.CustomerCode = mproduct.Customer.CustomerCode;
                    productSamMDTOs.Add(productSamMDTO);

                }
                else if (mproduct.ProductType == "1") { 
                    //1. add ตัวแม่
                    productSamMDTO = new ProductSamMDTO();
                    productSamMDTO.ProductCode = mproduct.ProductCode;
                    productSamMDTO.AC = mproduct.ProductAc;
                    productSamMDTO.AR = mproduct.ProductAr;
                    productSamMDTO.GAB = mproduct.ProductGab;
                    productSamMDTO.CustomerCode = mproduct.Customer.CustomerCode;
                    productSamMDTOs.Add(productSamMDTO);

                    //2. add ตัวลูก
                    List<Product> products = untilService.getProductsByCodepType(mproduct.ProductCode,session);

                    foreach (Product p in products) {
                        productSamMDTO = new ProductSamMDTO();
                        productSamMDTO.ProductCode = p.ProductCode;
                        productSamMDTO.AC = p.ProductAc;
                        productSamMDTO.AR = p.ProductAr;
                        productSamMDTO.GAB = p.ProductGab;
                        productSamMDTO.CustomerCode = p.Customer.CustomerCode;
                        productSamMDTOs.Add(productSamMDTO);
                    }
                 
                }


                if (productSamMDTOs.Count() > 0)
                {
                    dgvProduct.DataSource = productSamMDTOs;
                    FormatdgvProduct();
                }

                txtSaleOrder.Text = orderDTO.SaleOrder;
                txtMRPNo.Text = orderDTO.MrpNo;
                txtQtyOrder.Text = orderDTO.QtyOrder;
                txtFgSgtock.Text = orderDTO.FGStock;
                txtQty.Text = orderDTO.Qty;

            }
        }

        private void FormatdgvProduct()
        {
            if (dgvProduct.RowCount > 0)
            {
                dgvProduct.Columns["ProductCode"].HeaderText = "ProductCode";
                dgvProduct.Columns["AC"].HeaderText = "AC";
                dgvProduct.Columns["AR"].HeaderText = "AR";
                dgvProduct.Columns["GAB"].HeaderText = "GAB";
                dgvProduct.Columns["CustomerCode"].HeaderText = "CustomerCode";

                dgvProduct.Columns["Id"].Visible = false;

            }
        }

        private void cmdprint_Click(object sender, EventArgs e)
        {
            if (txtSaleOrder.Text.Trim() == "")
            {
                DevComponents.DotNetBar.MessageBoxEx.Show("กรุณาเลือกข้อมูลก่อน !!!", "ผลการตรวจสอบ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtSaleOrder.Focus();
                return;
            }

            NameplateCore newNamePlateCore = new NameplateCore();
            Orders order = untilService.getOrderNotDTOBySaleOrder(txtSaleOrder.Text.Trim(),session);

            newNamePlateCore.Orders = order;
            newNamePlateCore.LotNo = txtLotNo.Text.Trim();
            newNamePlateCore.Quantity = txtQtyRoll.Text.Trim();
            newNamePlateCore.InspectBy = txtInspectBy.Text.Trim();
            string _date2 = String.Format("{0:dd/MM/yyyy}", dtpInspecDate.Value);
            newNamePlateCore.InspecDate = Convert.ToDateTime(_date2);

            newNamePlateCore.Weight = txtWeight.Text.Trim();
            newNamePlateCore.PrintNum = txtNumPrint.Text.Trim();
            newNamePlateCore.Users = users;

            newNamePlateCore.PrintDate= DateTime.Now;
            newNamePlateCore.Status = "1";

            if (productSamMDTOs.Count == 1) {

                try
                {
                    
                    // ไม่มีลูก
                    string path = Application.StartupPath + "\\NameplateCore.btw";

                    btApp.Visible = false;
                    btformat = btApp.Formats.Open(path, true, "");

                    // barcode 
                    btformat.SetNamedSubStringValue("productcode1", order.Product.ProductCode);
                    btformat.SetNamedSubStringValue("productcode2", "");
                    btformat.SetNamedSubStringValue("customercode", order.Product.Customer.CustomerCode);
                    btformat.SetNamedSubStringValue("qty", order.QtyOrder);
                    btformat.SetNamedSubStringValue("saleorder", order.SaleOrder);
                    btformat.SetNamedSubStringValue("lotno", txtLotNo.Text.Trim());
                    btformat.SetNamedSubStringValue("insby", txtInspectBy.Text.Trim());
                    btformat.SetNamedSubStringValue("insdate", String.Format("{0:dd/MM/yyyy}", dtpInspecDate.Value));
                    btformat.SetNamedSubStringValue("weight", txtWeight.Text.Trim());
                    btformat.SetNamedSubStringValue("barcode", "2"+txtLotNo.Text.Trim()+""+ StringExt.StringFromLeft(order.Barcode,3));
           
                    btformat.PrintOut(false, false);

                    //print barcode

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    btformat.Close(BarTender.BtSaveOptions.btDoNotSaveChanges);
                }


            }
            else if (productSamMDTOs.Count == 2)
            {


                int i = 0;
                string productcode1 = "";

                foreach (ProductSamMDTO ps in productSamMDTOs)
                {
                    Product product = sampleFolderMService.getByCode(ps.ProductCode, session);

                    try
                    {

                        // ไม่มีลูก
                        string path = Application.StartupPath + "\\NameplateCore.btw";

                        btApp.Visible = false;
                        btformat = btApp.Formats.Open(path, true, "");

                        // barcode 

                        btformat.SetNamedSubStringValue("productcode1", productcode1);
                        btformat.SetNamedSubStringValue("productcode2", product.ProductCode);
                        btformat.SetNamedSubStringValue("customercode", product.Customer.CustomerCode);
                        btformat.SetNamedSubStringValue("qty", order.QtyOrder);
                        btformat.SetNamedSubStringValue("saleorder", order.SaleOrder);
                        btformat.SetNamedSubStringValue("lotno", txtLotNo.Text.Trim());
                        btformat.SetNamedSubStringValue("insby", txtInspectBy.Text.Trim());
                        btformat.SetNamedSubStringValue("insdate", String.Format("{0:dd/MM/yyyy}", dtpInspecDate.Value));
                        btformat.SetNamedSubStringValue("weight", txtWeight.Text.Trim());
                        btformat.SetNamedSubStringValue("barcode", "2" + txtLotNo.Text.Trim() + "" + StringExt.StringFromLeft(order.Barcode, 3));
                        productcode1 = product.ProductCode;
                        i++;
                        if (i == 1)
                        {
                            btformat.PrintOut(false, false);
                        }
                        //print barcode

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                    finally
                    {
                        btformat.Close(BarTender.BtSaveOptions.btDoNotSaveChanges);
                    }
                }

            }
            else {
 
                foreach (ProductSamMDTO ps in productSamMDTOs)
                {
                    Product product = sampleFolderMService.getByCode(ps.ProductCode, session);

                    try
                    {

                        // ไม่มีลูก
                        string path = Application.StartupPath + "\\NameplateCore.btw";

                        btApp.Visible = false;
                        btformat = btApp.Formats.Open(path, true, "");

                        // barcode 

                        btformat.SetNamedSubStringValue("productcode1", product.ProductCode);
                        btformat.SetNamedSubStringValue("productcode2", "");
                        btformat.SetNamedSubStringValue("customercode", product.Customer.CustomerCode);
                        btformat.SetNamedSubStringValue("qty", order.QtyOrder);
                        btformat.SetNamedSubStringValue("saleorder", order.SaleOrder);
                        btformat.SetNamedSubStringValue("lotno", txtLotNo.Text.Trim());
                        btformat.SetNamedSubStringValue("insby", txtInspectBy.Text.Trim());
                        btformat.SetNamedSubStringValue("insdate", String.Format("{0:dd/MM/yyyy}", dtpInspecDate.Value));
                        btformat.SetNamedSubStringValue("weight", txtWeight.Text.Trim());
                        btformat.SetNamedSubStringValue("barcode", "2" + txtLotNo.Text.Trim() + "" + StringExt.StringFromLeft(order.Barcode, 3));
                        
                     
                        btformat.PrintOut(false, false);
                      
                        //print barcode

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                    finally
                    {
                        btformat.Close(BarTender.BtSaveOptions.btDoNotSaveChanges);
                    }
                }

            }


            int result = namePlateCoreService.AddNamePlateCore(newNamePlateCore, session);
            if (result > -1)
            {
                Console.WriteLine("Add Complete");
                //MessageBox.Show("บันทึกข้อมูล เรียบร้อยแล้ว !!!", "ผลการทำงาน", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            else
            {
                Console.WriteLine("add Not Complete");
                //MessageBox.Show("ไม่สามารถบันทึกข้อมูลได้ !!!", "ผลการทำงาน", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }


            List<NameplateCorePrint> nameplateCorePrints = new List<NameplateCorePrint>();
            NameplateCorePrint nameplateCorePrint;

            nameplateCorePrint = new NameplateCorePrint();
            nameplateCorePrint.NameplateCore = newNamePlateCore;

            nameplateCorePrints.Add(nameplateCorePrint);
            newNamePlateCore.NameplateCorePrints = nameplateCorePrints;

            int updateresult = namePlateCoreService.UpdateNamePlateCore(newNamePlateCore, session);
            if (updateresult > -1)
            {
                Console.WriteLine("update Complete");
                MessageBox.Show("บันทึกข้อมูล เรียบร้อยแล้ว !!!", "ผลการทำงาน", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            else
            {
                Console.WriteLine("update Not Complete");
                MessageBox.Show("ไม่สามารถบันทึกข้อมูลได้ !!!", "ผลการทำงาน", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }



        }

    }
}
